# coding: utf-8
# @Author: ChuiZi
import os
import smtplib  # 邮件库
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText  # 多用途处理文本
from email.header import Header  # 邮件头
from email.mime.multipart import MIMEMultipart  # 邮件附件
from typing import List


class StpEmail:
    def __init__(self, userHost: str, passport: str, yourEmail: str, serve_type: str, serve_port="465"):
        self.__userhost = userHost  # 登录账号
        self.__passport = str(passport)  # 授权码
        self.__senderEmail = yourEmail  # 你的邮箱
        self.__serve_type = serve_type.lower()  # 邮箱供应商
        self.__serve_port = serve_port  # 服务器端口,一般是固定为465

        # 供应商对应的stp服务器
        self.__server_smtp = {
            "qq": "smtp.qq.com",
            "sina": "smtp.sina.com",
            "sinavip": "smtp.vip.sina.com",
            "sohu": "http://smtp.sohu.com",
            "126": "smtp.126.com",
            "139": "smtp.139.com",
            "163": "http://smtp.163.com",
        }

    def send(self, receivers: List, text, attaches=[]):
        """
        :param receivers: 邮件接受人,可以为字符串,多人则写成列表
        :param text: [标题,正文]的列表形式的邮件内容
        :param attaches: 附件的路径,单个可以为字符串,多个则由字符串组成列表
        :return:发送邮件
        """
        (textTitle, textContent) = text
        message = MIMEMultipart("mixed")

        message['Subject'] = Header(str.strip(str(textTitle)), "utf-8")  # 标题
        message.attach(MIMEText(str.strip(str(textContent)), "plain", "utf-8"))  # 正文

        # 附件处理流程
        if not isinstance(attaches, List):
            attaches = [attaches]
        if len(attaches):
            for attache in attaches:
                part = MIMEApplication(open(attache, 'rb').read())
                part.add_header('Content-Disposition', 'attachment', filename=os.path.split(attache)[1])
                message.attach(part)

        # <editor-fold desc="邮件发送流程">
        try:
            serve = smtplib.SMTP()
            serve.connect(self.__server_smtp[self.__serve_type])  # 连接smtp服务器
            serve.login(self.__userhost, self.__passport)  # 通过服务器验证
            serve.sendmail(self.__senderEmail, receivers, message.as_string())  # 发送邮件
            serve.quit()  # 退出链接

        except smtplib.SMTPRecipientsRefused:
            print('收件人拒收邮件')
        except smtplib.SMTPAuthenticationError:
            print('授权码错误')
        except smtplib.SMTPSenderRefused:
            print('未开启TLS服务,请在邮箱设置中开启')
        except smtplib.SMTPException as e:
            print(e.message)
        # </editor-fold>
